package org.jks.excel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.jks.report.model.SparePartsModel;
import org.jks.util.DateUtil;

public class SparePartsUtil {
	public static List<String> columns = new ArrayList<String>();
	static {
		columns.add("序号");
		columns.add("备品名称");
		columns.add("班组");
		columns.add("数量");
		columns.add("最小库存");
	}
	
	public static void export(HttpServletResponse response, List<SparePartsModel> models) {
		response.setContentType("applicationnd.ms-excel"); 
		
		try{
			String filename = java.net.URLEncoder.encode("备用备品清单", "UTF-8")+ "-"+DateUtil.toString(new Date(), "yyyyMMddHHmmss") + ".xls";
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + filename); 
			ServletOutputStream sos = response.getOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(sos);
			WritableSheet sheet = workbook.createSheet("sheet1", 0);
			int colCount = columns.size();
			for(int i=0; i<colCount; i++){
				sheet.setColumnView(i, 30);
			}
			sheet.mergeCells(0, 0, colCount-1, 0);
			WritableFont wf = new WritableFont(WritableFont.TIMES, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
			WritableCellFormat wcf = new WritableCellFormat(wf);
			wcf.setAlignment(Alignment.CENTRE);
			wcf.setBackground(Colour.GRAY_50);
			Label lab = null;
			lab = new Label(0, 0, "备用备品清单", wcf);
			sheet.addCell(lab);
			
			WritableFont wf1 = new WritableFont(WritableFont.TIMES, 12,
					WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLACK);
			WritableCellFormat wcf1 = new WritableCellFormat(wf1);
			wcf1.setBackground(Colour.GRAY_25);
			for(int i=0; i<colCount; i++){
				lab = new Label(i, 1, columns.get(i), wcf1);
				sheet.addCell(lab);
			}
			int index = 2;
			for(int rowIndex = 0; rowIndex<models.size(); rowIndex++){
				SparePartsModel m = models.get(rowIndex);
				
				lab = new Label(0, index, (rowIndex+1) + "");
				sheet.addCell(lab);
				
				lab = new Label(1, index, m.getDeviceType());
				sheet.addCell(lab);
				lab = new Label(2, index, m.getGroup());
				sheet.addCell(lab);
				lab = new Label(3, index, m.getCount());
				sheet.addCell(lab);
				lab = new Label(4, index, m.getMinInventory());
				sheet.addCell(lab);
				
				index++;
			}
			workbook.write();
			workbook.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}